package com.wx.forum.exception;

import com.wx.forum.common.AppResult;
import com.wx.forum.common.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 统一异常处理
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
    @ResponseBody
    @ExceptionHandler(ApplicationException.class) //要处理哪个异常
    public AppResult applicationException(ApplicationException e){
        e.printStackTrace(); //生产环境要删掉
        //打印日志
        log.error(e.getMessage());
        //处理空值
        if(e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        // 返回具体异常信息
        return AppResult.failed(e.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class) //要处理哪个异常
    public AppResult exceptionHandler(Exception e){
       e.printStackTrace();//打印栈信息
        //打印日志
        log.error(e.getMessage());
        //处理空值
        if(e.getMessage() == null || e.getMessage().equals("")){
            return AppResult.failed(ResultCode.ERROR_SERVICES);
        }
        // 返回具体异常信息
        return AppResult.failed(e.getMessage());
    }
}
